from django.http import JsonResponse
from django.shortcuts import render

# Create your views here.
from rest_framework.decorators import action
from rest_framework.permissions import IsAuthenticated

from rest_framework.response import Response
from rest_framework.views import APIView
from rest_framework.viewsets import ModelViewSet

from article.serializers import *
from users.models import *

from rest_framework.pagination import PageNumberPagination


# 分页
class Numpage(PageNumberPagination):
    page_size_query_param = 'pageNum'
    max_page_size = 10
    page_size = 5



class Numpage1(PageNumberPagination):
    page_size_query_param = 'pageNum'
    max_page_size = 10
    page_size = 10000000


# 文章-获取频道
class ChannelsView(ModelViewSet):
    queryset = Channel.objects.all()
    serializer_class = ChannelsModelSerializer

    pagination_class = Numpage1


# 文章操作
class ArticleCreatView(ModelViewSet):
    pagination_class = Numpage

    # 设置每个动作视图用的序列化器
    def get_serializer_class(self):
        # 文章创建
        if self.action == 'create':
            return ArticleCreateSerializer

        # 获取文章列表r'^article/(?P<pk>.+)/channel/$'
        if self.action == 'channel_articles':
            return ArticleChannelSerializer

        # 文章详情 /article/{id}/ GET
        if self.action == 'retrieve':
            return ArticleRetrieveSerializer

        # 文章评论
        if self.action == 'publish_comment':
            return CommentsSerializer

    # 获取(文章列表)查询集时走的函数
    def get_queryset(self):
        if self.action == 'channel_articles':
            pk = int(self.kwargs.get('pk'))
            if pk != -1:
                return Article.objects.filter(channel_id=pk)
        return Article.objects.all()

    # 获取一个(文章)对象时走的函数
    def get_object(self):
        obj = super(ArticleCreatView, self).get_object()
        # 当动作视图为文章详情时,该文章浏览量 +1
        if self.action == 'retrieve':
            obj.visits += 1
            obj.save()
        return obj

    # /article/发布文章
    def create(self, request, *args, **kwargs):
        data = request.data
        if request.user.is_anonymous:
            return Response({
                'message': '未登录',
                'success': 'False',
            }, status=400)
        # data['user'] = request.user.id
        # 有两个动作会访问这个creat函数, 每次动作使用的序列化器不一样
        bs = self.get_serializer(data=data)
        # 用不同的序列化器验证保存
        bs.is_valid(raise_exception=True)
        article = bs.save()

        return Response({
            'message': '发布成功',
            'success': True,
            'articleid': article.id
        })

    # 获取文章列表r'^article/(?P<pk>.+)/channel/$'
    @action(detail=True, url_path='channel')
    def channel_articles(self, request, pk):
        return self.list(self, request, pk)

    # 收藏/取消/article/{id}/collect/ PUT
    @action(detail=True, methods=['put'])
    def collect(self, request, pk):
        article = Article.objects.get(pk=pk)
        # 查出该文章的收藏用户集
        users = User.objects.filter(collected_articles=pk)
        # 判断用户是否在查询集中,
        if request.user in users:
            # 如果在,则功能为取消收藏
            article.collected_users.remove(request.user)
            data = '取消成功'
            return Response({
                'message': data,
                'success': True
            })
        else:
            # 如果不在,则功能为收藏
            article.collected_users.add(request.user)
            data = '收藏成功'
            return Response({
                'message': data,
                'success': True
            })

    # 文章评论 /users/{id}/publish_comment/ POST
    @action(detail=True, methods=['post'])
    def publish_comment(self, request, pk):
        return self.create(request, pk)


# 获取所有频道
class LabelsView(ModelViewSet):
    queryset = Label.objects.all()
    serializer_class = LabelsModelSerializer


# 搜索
from drf_haystack.viewsets import HaystackViewSet

class MySearchView(HaystackViewSet):
    index_models = [Article]
    serializer_class = ArticleIndexSerializer
    pagination_class = Numpage
